//  This file is part of Swordbible - http://www.swordwarrior.net
//  Copyright (C) 2003-2009 Manu Mital mital.manu@gmail.com

//  This program is free software; you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation; either version 2, or (at your option)
//  any later version.

//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.

//  You should have received a copy of the GNU General Public License
//  along with this program; if not, write to the Free Software Foundation,
//  Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.


// BibleTree.cpp : implementation file
//

#include <stdafx.h>
#include "SwordBible.h"
#include "BibleTree.h"
#include "SwordBibleDoc.h"
#include "SwordBibleView.h"
#include ".\bibletree.h"
#include "NotesPage.h"
#include "BottomPage.h"
#include "BiblePage.h"
#include "MainFrm.h"

// CBibleTree

IMPLEMENT_DYNCREATE(CBibleTree, CTreeView)

CBibleTree::CBibleTree()
{
}

CBibleTree::~CBibleTree()
{
}

BEGIN_MESSAGE_MAP(CBibleTree, CTreeView)
	ON_NOTIFY_REFLECT(TVN_SELCHANGED, OnTvnSelchanged)
	ON_MESSAGE(WM_TREE_SETSEL,OnSetSelection)
END_MESSAGE_MAP()


// CBibleTree diagnostics

#ifdef _DEBUG
void CBibleTree::AssertValid() const
{
	CTreeView::AssertValid();
}

void CBibleTree::Dump(CDumpContext& dc) const
{
	CTreeView::Dump(dc);
}
#endif //_DEBUG


// CBibleTree message handlers

void CBibleTree::PopulateTree()
{
		CTreeCtrl& treeCtrl =  GetTreeCtrl();  // Get handle to the tree control 
                                               // on the left window

		SetRedraw(FALSE);

		HICON icon_folder = ::AfxGetApp()->LoadIcon(IDI_ICON_FOLDER);
		HICON icon_file = ::AfxGetApp()->LoadIcon(IDI_ICON_FILE);

		m_image.Create(16,16, ILC_COLORDDB ,0,1);
		m_image.SetBkColor(RGB(255,255,255));
		m_image.Add(icon_folder);
		m_image.Add(icon_file);

	  treeCtrl.SetImageList(&m_image, TVSIL_NORMAL );

	
		// Add the names of the book to the tree control    
		for(int bookVar = 0; bookVar < 66 ; bookVar++)
	{
		// insert the name of the book in the tree and get a handle to the name
		HTREEITEM bookItem = treeCtrl.InsertItem(CSwordBibleDoc::bookCode[bookVar][1],0,0);

		// Obtain the number of chapters in this book book,converting from string to 
		// integer 
		int numberOfChapters = _tstoi(CSwordBibleDoc::bookCode[bookVar][2]);
	    
		CString numStr;   // a temporary string to hold the chapter number for printing

		// insert chapter numbers into tree for each book
		for(int chapterVar = 1; chapterVar <= numberOfChapters; chapterVar++)
		{	numStr.Format(_T("%d"),chapterVar);
			treeCtrl.InsertItem(numStr,1,1, bookItem);
		}


	// end of outer loop
	}


	
	// add background effect
	treeCtrl.SetBkColor( RGB(245,255,255));

	

	SetRedraw(TRUE);

	
	//treeCtrl.Select(treeCtrl.GetRootItem(), TVGN_CARET);
	//treeCtrl.Expand(treeCtrl.GetRootItem(), TVE_COLLAPSE);
	 OnSetSelection(0,0);

 // end of the void function
	return;
}

void CBibleTree::OnInitialUpdate()
{
	CTreeView::OnInitialUpdate();
	PopulateTree();
}

BOOL CBibleTree::PreCreateWindow(CREATESTRUCT& cs)
{
	// TODO: Add your specialized code here and/or call the base class
	// add buttons to the left window tree control
	cs.style |= (TVS_HASLINES |TVS_LINESATROOT|TVS_SHOWSELALWAYS|
			TVS_DISABLEDRAGDROP|TVS_SINGLEEXPAND );

	return CTreeView::PreCreateWindow(cs);
}


void CBibleTree::OnTvnSelchanged(NMHDR *pNMHDR, LRESULT *pResult)
{
	LPNMTREEVIEW pNMTreeView = reinterpret_cast<LPNMTREEVIEW>(pNMHDR);
	// TODO: Add your control notification handler code here
	*pResult = 0;

	// Get a handle to the tree control object
   CTreeCtrl& treeCtrl =  GetTreeCtrl();

   // Get the newly selected Tree Control item
   HTREEITEM selected = treeCtrl.GetSelectedItem();

   // Get parent item of the slected item
   HTREEITEM parent_of_selected = treeCtrl.GetParentItem(selected);

   
   // Get the text of the selected item
   CString sel_text = treeCtrl.GetItemText(selected);

   
   // get the name of the book of the bible that is selected
   CString parent_text = treeCtrl.GetItemText(parent_of_selected);

   // no parent (user has selected a book title) => change the book to
   // sel_text and chapter to 1
  if(parent_of_selected == NULL)   
  {  
	  CString newKey;
	 newKey.Format(_T("%s %d:%d"),sel_text,1,1);
     CSwordBibleDoc::key = (CStringA) newKey;
  }
	  // change the current key
	 
   // the item has parent
   else  {
	  CString parent_text = treeCtrl.GetItemText(parent_of_selected);
	  CString newKey;
	  newKey.Format(_T("%s %s:%d"),parent_text,sel_text,1);
      CSwordBibleDoc::key = (CStringA) newKey;
   }

 
   // the new key has been set
  	// Change the display in the bible, and if synchronize is TRUE, change the 
  // display in the notes/commentary
	CWnd * pWnd = AfxGetMainWnd();

  //Add to verse history
  ((CMainFrame*)pWnd)->AddCurrentVerseToHistory();

	CBiblePage::ActiveMainFrameCommand = _T("ShowChapter");
	pWnd->SendMessageToDescendants(ID_BIBLEPAGE_COMMAND, 0,0);

	if(CSwordBibleDoc::notesSynch)
	{
	CNotesPage::ActiveMainFrameCommand = _T("BibleSynch");
	pWnd->SendMessageToDescendants(ID_NOTES_COMMAND,0,0);
	}

	if(CSwordBibleDoc::bottomSynch)
	{
	CBottomPage::ActiveMainFrameCommand = _T("BibleSynch");
	pWnd->SendMessageToDescendants(ID_COMMENTARY_COMMAND,0,0);
	}


}


LONG CBibleTree::OnSetSelection(UINT, LONG)
{
	CTreeCtrl& treeCtrl =  GetTreeCtrl();
	
	HTREEITEM hBrother = treeCtrl.GetRootItem();

	int max = CSwordBibleDoc::Book();  //min:1 max:66 
	 
	if(max > 66) max = 66;

   for(int i = 1; i < max; i++) {
       hBrother = treeCtrl.GetNextSiblingItem(hBrother);
		}


	HTREEITEM hChild = treeCtrl.GetChildItem(hBrother);

	max = 1;
	int numChap = CSwordBibleDoc::Chapter();

	while(max < numChap ) {

	hChild = treeCtrl.GetNextSiblingItem(hChild);
	max++;
	
	}

	treeCtrl.SelectItem(hChild);


return 0L;

}


BOOL CBibleTree::CreateView(CWnd* pParent, CCreateContext* pContext)
{
    DWORD dwStyle = AFX_WS_DEFAULT_VIEW;
    dwStyle &= ~WS_BORDER;

    // Create with the right size (wrong position)
    CRect rect(0,0,300,300);

    /** Note:> Upon this Create(...) WM_CREATE message is sent
        so OnCreate(..) will be called
        pContext != NULL then this will be added or registered
        to the document i.e. pContext->m_pCurrentDoc->AddView(this);
        this attaches this view to the current document
        this function also sets the view's document pointer
        to this document.
    */

    if (!Create(NULL, NULL, dwStyle,
        rect, pParent, AFX_IDW_PANE_FIRST, pContext))
    {
        TRACE0("Warning: couldn't create treeview pane!. \n");
        return FALSE;
    }

    return TRUE;
}

